package com.apkicon.processor;

import com.apkicon.model.IconInfo;
import com.apkicon.parser.OptimizedApkResourceResolver;
import net.dongliu.apk.parser.ApkFile;
import javax.imageio.ImageIO;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.ByteArrayInputStream;

/**
 * Android原生风格的Adaptive Icon处理器
 * 严格按照Android原生AdaptiveIconDrawable的实现方式
 */
public class NativeStyleAdaptiveIconProcessor implements IconProcessor {
    
    @Override
    public IconInfo processIcon(com.apkicon.parser.ApkParserLibrary.ApkInfo apkInfo, 
                               com.apkicon.parser.ApkParserLibrary.IconResource iconResource, 
                               int targetSize) throws Exception {
        try (ApkFile apk = new ApkFile(apkInfo.getApkFile())) {
            System.out.println("🔍 处理Adaptive Icon (原生风格): " + iconResource.getPath());
            
            // 1. 解析Adaptive Icon资源
            OptimizedApkResourceResolver.AdaptiveIconResources resources = 
                OptimizedApkResourceResolver.resolveAdaptiveIconResources(apk, iconResource.getPath());
            
            System.out.println("📱 解析结果:");
            System.out.println("   背景: " + resources.getBackgroundPath());
            System.out.println("   前景: " + resources.getForegroundPath());
            
            // 2. 加载背景和前景Drawable
            BufferedImage backgroundDrawable = loadDrawable(apk, resources.getBackgroundPath());
            BufferedImage foregroundDrawable = loadDrawable(apk, resources.getForegroundPath());
            
            if (backgroundDrawable == null || foregroundDrawable == null) {
                throw new IllegalArgumentException("无法加载背景或前景Drawable");
            }
            
            // 3. 使用原生方式渲染
            BufferedImage iconImage = renderNativeStyle(backgroundDrawable, foregroundDrawable, targetSize);
            
            if (iconImage == null) {
                throw new IllegalArgumentException("Failed to render Adaptive Icon: " + iconResource.getPath());
            }
            
            System.out.println("✅ Adaptive Icon渲染完成 (原生风格) (" + targetSize + "x" + targetSize + ")");
            
            return new IconInfo(iconImage, IconInfo.IconType.ADAPTIVE_ICON, iconResource.getPath());
        }
    }
    
    /**
     * 加载Drawable资源
     */
    private BufferedImage loadDrawable(ApkFile apk, String drawablePath) {
        if (drawablePath == null) return null;
        
        try {
            byte[] data = apk.getFileData(drawablePath);
            if (data != null) {
                return ImageIO.read(new ByteArrayInputStream(data));
            }
        } catch (Exception e) {
            System.err.println("无法加载Drawable: " + drawablePath + " - " + e.getMessage());
        }
        
        return null;
    }
    
    /**
     * 原生风格的Adaptive Icon渲染
     * 严格按照Android原生AdaptiveIconDrawable的实现
     */
    private BufferedImage renderNativeStyle(BufferedImage backgroundDrawable, BufferedImage foregroundDrawable, int targetSize) {
        try {
            // 1. 创建LayerDrawable数组 (对应Android的Drawable[] layers)
            BufferedImage[] layers = new BufferedImage[2];
            layers[0] = backgroundDrawable;  // 背景层
            layers[1] = foregroundDrawable;  // 前景层
            
            // 2. 创建输出Bitmap (对应Android的Bitmap.createBitmap)
            BufferedImage bitmap = new BufferedImage(targetSize, targetSize, BufferedImage.TYPE_INT_ARGB);
            Graphics2D canvas = bitmap.createGraphics();
            
            try {
                // 3. 设置高质量渲染 (对应Android Canvas的高质量设置)
                setupNativeQualityRendering(canvas);
                
                // 4. 设置绘制边界 (对应Android的setBounds)
                Rectangle bounds = new Rectangle(0, 0, targetSize, targetSize);
                
                // 5. 分层绘制 (对应Android的LayerDrawable.draw)
                drawLayerDrawable(canvas, layers, bounds);
                
            } finally {
                canvas.dispose();
            }
            
            return bitmap;
            
        } catch (Exception e) {
            System.err.println("原生风格渲染失败: " + e.getMessage());
            return renderFallbackStyle(backgroundDrawable, foregroundDrawable, targetSize);
        }
    }
    
    /**
     * 设置原生质量渲染
     */
    private void setupNativeQualityRendering(Graphics2D g2d) {
        // Android原生Canvas的高质量设置
        g2d.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
        g2d.setRenderingHint(RenderingHints.KEY_RENDERING, RenderingHints.VALUE_RENDER_QUALITY);
        g2d.setRenderingHint(RenderingHints.KEY_INTERPOLATION, RenderingHints.VALUE_INTERPOLATION_BICUBIC);
        g2d.setRenderingHint(RenderingHints.KEY_COLOR_RENDERING, RenderingHints.VALUE_COLOR_RENDER_QUALITY);
        g2d.setRenderingHint(RenderingHints.KEY_ALPHA_INTERPOLATION, RenderingHints.VALUE_ALPHA_INTERPOLATION_QUALITY);
        g2d.setRenderingHint(RenderingHints.KEY_DITHERING, RenderingHints.VALUE_DITHER_ENABLE);
        
        // Android特有的渲染设置
        g2d.setRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING, RenderingHints.VALUE_TEXT_ANTIALIAS_ON);
        g2d.setRenderingHint(RenderingHints.KEY_FRACTIONALMETRICS, RenderingHints.VALUE_FRACTIONALMETRICS_ON);
    }
    
    /**
     * 绘制LayerDrawable (对应Android的LayerDrawable.draw)
     */
    private void drawLayerDrawable(Graphics2D canvas, BufferedImage[] layers, Rectangle bounds) {
        // 按照Android LayerDrawable的绘制顺序
        for (int i = 0; i < layers.length; i++) {
            BufferedImage layer = layers[i];
            if (layer != null) {
                drawLayer(canvas, layer, bounds, i);
            }
        }
    }
    
    /**
     * 绘制单个Layer
     */
    private void drawLayer(Graphics2D canvas, BufferedImage layer, Rectangle bounds, int layerIndex) {
        if (layerIndex == 0) {
            // 背景层：填满整个区域 (对应Android AdaptiveIconDrawable.getBackground())
            drawBackgroundLayer(canvas, layer, bounds);
        } else if (layerIndex == 1) {
            // 前景层：在安全区域内绘制 (对应Android AdaptiveIconDrawable.getForeground())
            drawForegroundLayer(canvas, layer, bounds);
        }
    }
    
    /**
     * 绘制背景层 (对应Android AdaptiveIconDrawable.getBackground().draw())
     */
    private void drawBackgroundLayer(Graphics2D canvas, BufferedImage background, Rectangle bounds) {
        // 先填充白色背景（修复透明区域问题）
        canvas.setColor(Color.WHITE);
        canvas.fillRect(bounds.x, bounds.y, bounds.width, bounds.height);
        
        // Android原生：背景层填满整个108dp区域
        canvas.drawImage(background, 
                        bounds.x, bounds.y, 
                        bounds.width, bounds.height, 
                        null);
    }
    
    /**
     * 绘制前景层 (对应Android AdaptiveIconDrawable.getForeground().draw())
     */
    private void drawForegroundLayer(Graphics2D canvas, BufferedImage foreground, Rectangle bounds) {
        // Android原生：前景层在72dp安全区域内绘制
        // 计算安全区域 (对应Android的getSafeZone)
        Rectangle safeZone = calculateSafeZone(bounds);
        
        // 计算前景层的最佳尺寸和位置
        Rectangle foregroundBounds = calculateForegroundBounds(foreground, safeZone);
        
        // 绘制前景层
        canvas.drawImage(foreground,
                        foregroundBounds.x, foregroundBounds.y,
                        foregroundBounds.width, foregroundBounds.height,
                        null);
    }
    
    /**
     * 计算安全区域 (对应Android AdaptiveIconDrawable的安全区域)
     * Android规范：108dp总尺寸，72dp安全区域，18dp外层
     */
    private Rectangle calculateSafeZone(Rectangle totalBounds) {
        int totalSize = totalBounds.width;
        
        // 计算安全区域尺寸 (72dp / 108dp = 2/3)
        int safeSize = (int) (totalSize * 2.0 / 3.0);
        
        // 计算安全区域位置 (居中)
        int safeX = (totalSize - safeSize) / 2;
        int safeY = (totalSize - safeSize) / 2;
        
        return new Rectangle(safeX, safeY, safeSize, safeSize);
    }
    
    /**
     * 计算前景层绘制边界
     */
    private Rectangle calculateForegroundBounds(BufferedImage foreground, Rectangle safeZone) {
        int foregroundWidth = foreground.getWidth();
        int foregroundHeight = foreground.getHeight();
        
        // 计算缩放比例，保持宽高比
        double scaleX = (double) safeZone.width / foregroundWidth;
        double scaleY = (double) safeZone.height / foregroundHeight;
        double scale = Math.min(scaleX, scaleY);
        
        // 计算缩放后的尺寸
        int scaledWidth = (int) (foregroundWidth * scale);
        int scaledHeight = (int) (foregroundHeight * scale);
        
        // 计算居中位置
        int x = safeZone.x + (safeZone.width - scaledWidth) / 2;
        int y = safeZone.y + (safeZone.height - scaledHeight) / 2;
        
        return new Rectangle(x, y, scaledWidth, scaledHeight);
    }
    
    /**
     * Fallback渲染方式
     */
    private BufferedImage renderFallbackStyle(BufferedImage backgroundDrawable, BufferedImage foregroundDrawable, int targetSize) {
        try {
            BufferedImage bitmap = new BufferedImage(targetSize, targetSize, BufferedImage.TYPE_INT_ARGB);
            Graphics2D canvas = bitmap.createGraphics();
            
            try {
                canvas.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
                canvas.setRenderingHint(RenderingHints.KEY_INTERPOLATION, RenderingHints.VALUE_INTERPOLATION_BILINEAR);
                
                // 简单叠加
                if (backgroundDrawable != null) {
                    canvas.drawImage(backgroundDrawable, 0, 0, targetSize, targetSize, null);
                }
                
                if (foregroundDrawable != null) {
                    int innerSize = (int) (targetSize * 0.67);
                    int offset = (targetSize - innerSize) / 2;
                    canvas.drawImage(foregroundDrawable, offset, offset, innerSize, innerSize, null);
                }
                
            } finally {
                canvas.dispose();
            }
            
            return bitmap;
            
        } catch (Exception e) {
            System.err.println("Fallback渲染失败: " + e.getMessage());
            return null;
        }
    }
}
